package com.tao.xitong.security;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    private JwtRequestFilter jwtRequestFilter;

    /**
     * 配置Security过滤器链
     * 此方法用于定制Spring Security的安全过滤器链，以实现JWT认证和授权请求的处理
     *
     * @param http HttpSecurity对象，用于配置Web应用的HTTP请求的安全性
     * @return 返回配置好的SecurityFilterChain对象
     * @throws Exception 如果配置过程中出现错误，则可能抛出此异常
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 禁用CSRF保护，因为本应用可能不支持CSRF令牌，或者已经使用其他方式进行了保护
        http.csrf(AbstractHttpConfigurer::disable);

        // 配置请求的授权规则
        http.authorizeHttpRequests(auth -> auth
                // 对所有/api/auth/**路径的请求允许未认证访问，以便用户可以登录和注册
                .requestMatchers("/api/auth/**").permitAll()
                // 所有其他请求必须经过认证才能访问
                .anyRequest().authenticated()
        );

        // 配置无状态会话管理，以支持JWT认证
        http.sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        );

        // 在UsernamePasswordAuthenticationFilter之前添加JwtRequestFilter过滤器，以实现JWT认证
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

        // 返回构建好的SecurityFilterChain对象
        return http.build();
    }
}